
local wx = require "wx"
local rcr = require "barf.rcr"
local _G = _G
local ipairs,pairs,error,setmetatable,tostring,tonumber
    = ipairs,pairs,error,setmetatable,tostring,tonumber
local strbyte, strsub, strmatch, strrep, strchar, strformat
    = string.byte, string.sub, string.match, string.rep, string.char, string.format
local tconcat = table.concat
local bit = require "bit"


module "barf.editors"


function shopstock(info, parentWindow)
    local rom = _G.rom;
    
    local stocklists = {};
    for i = 1,info.count do
        local ptr = rom:uint16_le(info.rom, info.bank, info.start + (2*(i-1)));
        ptr = bit.band(ptr, bit.bnot(info.ptr_OR));
        
        local list = {}
        while true do
            local item_id = rom:uint8(info.rom, info.bank, ptr)
            if (item_id == 0xFF) then  break;  end
            list[#list+1] = item_id
            ptr = ptr + 1
        end
        
        stocklists[i] = list
    end
    
    parentWindow.Sizer = wx.wxBoxSizer(wx.wxVERTICAL);
    
    -- Tree view of stock in each shop
    local stockTree = wx.wxTreeCtrl(
        parentWindow,
        wx.wxID_ANY,
        wx.wxDefaultPosition,
        wx.wxDefaultSize,
        wx.wxTR_DEFAULT_STYLE + wx.wxTR_HIDE_ROOT
    );
        
    parentWindow.Sizer:Add(stockTree, 1, wx.wxEXPAND + wx.wxALL, 0);
    
    parentWindow:Layout();
    
    local itemAddress = rom.romlib.addresses.shops.items;
    local function itemName(id)
        local ptrptr = rom:uint16_le(itemAddress.rom, itemAddress.bank, itemAddress.start + (2*id));
        ptrptr = bit.band(ptrptr, bit.bnot(itemAddress.ptr_OR));
        return rom:string(itemAddress.rom, itemAddress.bank, ptrptr);
    end
    
    local root = stockTree:AddRoot("Shops")
    for shop_index,stocklist in ipairs(stocklists) do
        local shop_node = stockTree:AppendItem(root, "Stock List #" .. shop_index)
        for i,item_id in ipairs(stocklist) do
            stockTree:AppendItem(shop_node, itemName(item_id));
            --stockTree:AppendItem(shop_node, "Item #" .. item_id)
        end
    end
end

return shopstock;
